﻿using System;
using System.Drawing;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace CubeStone.Wang.Utilities
{
    /// <summary>
    /// 二维码、条形码帮助类
    /// </summary>
    public class CodeHelper
    {
        /// <summary>
        /// 二维码生成
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="width">宽度（默认100）</param>
        /// <param name="height">高度（默认100）</param>
        /// <param name="margin">边距（较诡异，慎用，默认0）</param>
        /// <returns>Bitmap</returns>
        public static Bitmap QRCode(string content, int width = 100, int height = 100, int margin = 0)
        {
            if (string.IsNullOrEmpty(content))
            {
                return null;
            }
            else if (width <= 0 || height <= 0 || margin < 0)
            {
                return null;
            }
            else
            {
                EncodingOptions encodingOptions = null;
                BarcodeWriter barcodeWriter = null;
                encodingOptions = new QrCodeEncodingOptions()
                {
                    DisableECI = true,
                    CharacterSet = "UTF-8",
                    Width = width,
                    Height = height,
                    Margin = margin
                };
                barcodeWriter = new BarcodeWriter();
                barcodeWriter.Format = BarcodeFormat.QR_CODE;
                barcodeWriter.Options = encodingOptions;
                return barcodeWriter.Write(content);
            }
        }

        /// <summary>
        /// 条形码生成
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="width">宽度（默认100）</param>
        /// <param name="height">高度（默认50）</param>
        /// <param name="margin">左右边距（按一半算，默认0）</param>
        /// <returns>Bitmap</returns>
        public static Bitmap ITFCode(string content, int width = 100, int height = 50, int margin = 0)
        {
            if(string.IsNullOrEmpty(content))
            {
                return null;
            }
            else if(width <= 0 || height <= 0 || margin < 0)
            {
                return null;
            }
            else
            {
                EncodingOptions encodingOptions = null;
                BarcodeWriter barcodeWriter = null;
                encodingOptions = new EncodingOptions()
                {
                    Width = width,
                    Height = height,
                    Margin = margin
                };
                barcodeWriter = new BarcodeWriter();
                barcodeWriter.Format = BarcodeFormat.ITF;
                barcodeWriter.Options = encodingOptions;
                return barcodeWriter.Write(content);
            }
        }
    }
}